package com.beici.waterghost.service.impl;

import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beici.waterghost.mapper.*;
import com.beici.waterghost.model.*;
import com.beici.waterghost.service.nodeService;
import com.beici.waterghost.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

@Service
public class nodeServiceImpl implements nodeService {
    @Autowired
    private nodeMapper nodeServer;
    @Autowired
    private userMapper userServer;
    @Autowired
    private albumMapper albumServer;
    @Autowired
    private commentsMapper commentsServer;
    @Autowired
    private collentMapper collentService;

    @Override
    public resultes quertyUserNodes(Integer userId) {
        List<node> user_id = nodeServer.selectList(new QueryWrapper<node>().eq("user_id", userId).orderByDesc("node_time"));
        System.out.println(user_id);
        return resultes.success("获取成功",user_id);
    }

    @Override
    public resultes quertyNodeAll() {
        // 查询全部文章
        List<node> user_id = (List<node>) takeUtils.verfitySelect(nodeServer.queryChaosNode());
        user user = null;
        try {
             user = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }catch (ClassCastException e){
            System.out.println(e.getMessage());

        }
        // 查询文章所对应的用户
        for (node node : user_id) {
            Integer userId = node.getUserId();
            // 塞进用户信息
            user u = userServer.selectOne(new QueryWrapper<user>().eq("user_id", userId).select("user_name,user_id,user_header"));
            node.setUserName(u.getUserName());
            node.setUserHeader(u.getUserHeader());
            // 处理图片
            String[] split = node.getNodeImages().split(",");
            node.setArrImgs(split);
            // 查询用户是否收藏了该帖子
            if (user!=null){
                boolean b = userCollentNode(node.getNodeId(), user.getUserId());
                System.out.println(b);
                node.setCollentState(b);
            }else {
                node.setCollentState(true);
            }
        }
        return resultes.success("获取成功",user_id);
    }

    public resultes quertyOBNodeAll(Integer obId) {
        // 查询全部文章
        List<node> user_id = (List<node>) takeUtils.verfitySelect(nodeServer.selectList(new QueryWrapper<node>().eq("user_id",obId).orderByDesc("node_Time")));
        user user = null;
        try {
            user = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }catch (ClassCastException e){
            System.out.println(e.getMessage());

        }
        // 查询文章所对应的用户
        for (node node : user_id) {
            Integer userId = node.getUserId();
            // 塞进用户信息
            user u = userServer.selectOne(new QueryWrapper<user>().eq("user_id", userId).select("user_name,user_id,user_header"));
            node.setUserName(u.getUserName());
            node.setUserHeader(u.getUserHeader());
            // 处理图片
            String[] split = node.getNodeImages().split(",");
            node.setArrImgs(split);
            // 查询用户是否收藏了该帖子
            if (user!=null){
                boolean b = userCollentNode(node.getNodeId(), user.getUserId());
                System.out.println(b);
                node.setCollentState(b);
            }else {
                node.setCollentState(true);
            }
        }
        return resultes.success("获取成功",user_id);
    }

    public resultes todayFriendsNode(Integer obId) {
        // 查看好友今天发布的帖子
        List<node> user_id = nodeServer.selectList(new QueryWrapper<node>().eq("user_id",obId).like("node_time", dateUtils.getCurrentDate()+"%"));
        user user = null;
        try {
            user = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }catch (ClassCastException e){
            System.out.println(e.getMessage());

        }
        // 查询文章所对应的用户
        for (node node : user_id) {
            Integer userId = node.getUserId();
            // 塞进用户信息
            user u = userServer.selectOne(new QueryWrapper<user>().eq("user_id", userId).select("user_name,user_id,user_header"));
            node.setUserName(u.getUserName());
            node.setUserHeader(u.getUserHeader());
            // 处理图片
            String[] split = node.getNodeImages().split(",");
            node.setArrImgs(split);
            // 查询用户是否收藏了该帖子
            if (user!=null){
                boolean b = userCollentNode(node.getNodeId(), user.getUserId());
                System.out.println(b);
                node.setCollentState(b);
            }else {
                node.setCollentState(true);
            }
        }
        return resultes.success("获取成功",user_id);
    }


    public resultes quertyNode(Long nodeId) {
        // 查询全部文章
        node node = (node) takeUtils.verfitySelect(nodeServer.selectOne(new QueryWrapper<node>().eq("node_id",nodeId).select("node_id","user_id","node_mess","node_images","node_look","node_time","node_like")));
        // 查询文章所对应的用户
            Integer userId = node.getUserId();
            // 塞进用户信息
            user u = userServer.selectOne(new QueryWrapper<user>().eq("user_id", userId).select("user_name,user_id,user_header"));
            node.setUserName(u.getUserName());
            node.setUserHeader(u.getUserHeader());
            // 处理图片
            String[] split = node.getNodeImages().split(",");
            node.setArrImgs(split);
            return resultes.success("获取成功",node);
    }
    private boolean userCollentNode(Long nodeId,Integer userId){
        Integer integer = collentService.selectCount(new QueryWrapper<collent>().eq("node_id", nodeId).eq("user_id", userId));
        System.out.println(integer);
        return integer>0?false:true;
    }

    @Override
    public resultes delNode(Long nodeId,Integer userId) {
        node node_id = (node) takeUtils.verfitySelect(nodeServer.selectOne(new QueryWrapper<node>().eq("node_id", nodeId).select("user_id")));
        if (userId.equals(node_id.getUserId())){
            takeUtils.vefitiyINSERT(nodeServer.delete(new QueryWrapper<node>().eq("node_id", nodeId)));
            return resultes.success("删除成功",true);
        }
        return resultes.error("不是本人操作");
    }

    @Override
    @Transactional
    public resultes queryDetailsInfo(Long nodeId) {
        // 查出文章所有内容 取出标签、人的信息、评论的信息
        node node = (com.beici.waterghost.model.node) takeUtils.verfitySelect(nodeServer.selectOne(new QueryWrapper<node>().eq("node_id", nodeId).select("user_id,node_time,node_id,node_tag,node_mess,node_images,node_like,node_look")));
        user u = null;
        try {
            u = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }catch (NullPointerException e){
            System.out.println(e.getMessage());
        }catch (ClassCastException e){
            System.out.println(e.getMessage());
        }
        if (u!=null){
            boolean b = userCollentNode(nodeId, u.getUserId());
            node.setCollentState(b);
        }
        // 浏览+1
        node.setNodeLook(node.getNodeLook()+1);
        nodeServer.updateById(node);
        Integer userId = node.getUserId();
        // 查出人的信息
        user user_id = userServer.selectOne(new QueryWrapper<user>().eq("user_id", userId).select("user_id,user_name,user_mess,user_sv,user_vip,user_header"));
        userAlbumInfo userAlbum = new userAlbumInfo(
                userId,
                user_id.getUserName(),
                user_id.getUserSv(),
                user_id.getUserVip(),
                user_id.getUserMess(),
                nodeServer.selectCount(new QueryWrapper<node>().eq("user_id",user_id.getUserId())),
                user_id.getUserHeader());
        // 查出标签的信息
        String[] nodeTag = node.getNodeTag().split(",");
        List list = new ArrayList();
        if (node.getNodeTag()!=null){
            for (int i = 0; i < nodeTag.length; i++) {
                album album = albumServer.selectOne(new QueryWrapper<album>().eq("ab_id", nodeTag[i]).select("ab_name,ab_id"));
                Map nodeTags = new HashMap();
                nodeTags.put("abName",album.getAbName());
                nodeTags.put("abId",album.getAbId());
                list.add(nodeTags);
            }
        }
        // 查出图片
        String[] split = node.getNodeImages().split(",");
        node.setArrImgs(split);
        // 查评论
        List<comments> commens = commentsServer.selectList(new QueryWrapper<comments>().eq("node_id", nodeId).select("user_id,node_id,com_date,com_mess"));
        for (comments commen : commens) {
            user user = userServer.selectOne(new QueryWrapper<user>().eq("user_id", commen.getUserId()).select("user_name,user_header"));
            commen.setUserName(user.getUserName());
            commen.setUserHeader(user.getUserHeader());
            // 查出是否为自己关注
        }
        Map map = new HashMap();
        map.put("userInfo",userAlbum);
        map.put("tag",list);
        map.put("node",node);
        map.put("comments",commens);

        return resultes.success("获取成功",map);


    }

    @Override
    public resultes addNode(node node) {
        long longRandom = idRandom.getLongRandom();
        node.setNodeId(longRandom);
        // 判断内容是否合法
        if (node.getNodeMess().length()>2){
            boolean b = contextUtils.veifityContext(node.getNodeMess());
            if (!b){
                return resultes.error("请检测内容不得出现违法词汇");
            }
        }
        node.setNodeTime(new Date());
        takeUtils.vefitiyINSERT(nodeServer.insert(node));
        urlSend.baiDuSend("http://data.zz.baidu.com/urls?site=https://www.waghost.com&token=PDsOBOpIJZnvppeC"
                ,new String[]{"https://www.waghost.com/detail/"+longRandom}
        );
        // 用户加经验
        return resultes.success("发布成功",longRandom);
    }

}
